package com.manster.util;

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.Date;
/**
 * @Author manster
 * @Date 2022/3/13
 **/
@Component
public class JwtUtils {

    // 生成jwt
    public static String generateToken(String username) {

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * Const.EXPIRE);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)// 1天过期
                .signWith(SignatureAlgorithm.HS512, Const.SECRET)
                .compact();
    }

    // 解析jwt
    public static Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(Const.SECRET)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    // jwt是否过期
    public static boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

}
